<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <!-- 添加分类按钮 -->
      <el-row>
        <el-col>
          <el-button
            type="primary"
            @click="addCate"
          >添加分类</el-button>
        </el-col>
      </el-row>

      <!-- 商品分类列表,引入运行依赖tree-table -->
      <tree-table
        :data="cateResultTreeList"
        :columns="columns"
        :selection-type="false"
        :expand-type="false"
        show-index
        index-text="#"
        border
      >
        <!-- 是否有效 -->
        <template
          slot="isOk"
          slot-scope="scope"
        >
          <i
            class="el-icon-success"
            style="color:lightgreen;font-size:28px"
            v-if="scope.row.cat_deleted !== 'false'"
          ></i>
          <i
            class="el-icon-error"
            style="color:red;
            font-size:28px"
            v-else
          ></i>
        </template>
        <!-- 等级 -->
        <template
          slot="level"
          slot-scope="scope"
        >
          <el-tag v-if="scope.row.cat_level == 0">一级</el-tag>
          <el-tag
            v-if="scope.row.cat_level == 1"
            type="success"
          >二级</el-tag>
          <el-tag
            v-if="scope.row.cat_level == 2"
            type="warning"
          >三级</el-tag>
        </template>

        <!-- 操作 -->
        <template
          slot="operation"
          slot-scope="scope"
        >
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="mini"
            @click="editCateGoodsName(scope.row.cat_id, scope.row.cat_name)"
          >编辑</el-button>
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="deleteRightRoles(scope.row.cat_id)"
          >删除</el-button>
        </template>
      </tree-table>

      <!-- 分页功能 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>

      <!-- 添加分类弹出对话框 -->
      <el-dialog
        title="添加分类商品"
        :visible.sync="addCatedialogVisible"
        width="50%"
        @close="clearFromInfo"
      >
        <!-- 添加分类商品表单 -->
        <el-form
          ref="addCateFormRef"
          :model="addCateFormValue"
          label-width="80px"
          :rules="addCateRules"
        >
          <el-form-item
            label="分类名称"
            prop="cat_name"
          >
            <el-input v-model="addCateFormValue.cat_name"></el-input>
          </el-form-item>
          <!-- 添加商品分类 -->
          <el-form-item label="父级名称">
            <!-- options所绑定的数据源 -->
            <!-- props是配置对象 -->
            <el-cascader
              props.expandTrigger="hover"
              :options="parentCateList"
              v-model="cateSelectedOptions"
              :props="catePropsObj"
              @change="cateHandleChange"
            >
            </el-cascader>
          </el-form-item>
        </el-form>
        <span
          slot="footer"
          class="dialog-footer"
        >
          <el-button @click="addCatedialogVisible = false">取 消</el-button>
          <el-button
            type="primary"
            @click="addCateGoods"
          >确 定</el-button>
        </span>
      </el-dialog>

      <!-- 商品分类修改功能 -->

      <el-dialog
        title="修改商品"
        :visible.sync="editCateDialogVisible"
        width="30%"
        @close="clearEditFromData"
      >
        <!-- 修改表单 -->
        <el-form
          ref="editCateGoodsNameRef"
          :model="editCateGoodsNameForm"
          label-width="80px"
          :rules="editCateGoodsNameRules"
        >
          <el-form-item
            label="商品名称"
            prop="cate_name"
          >
            <el-input v-model="editCateGoodsNameForm.cat_name"></el-input>
          </el-form-item>
        </el-form>
        <span
          slot="footer"
          class="dialog-footer"
        >
          <el-button @click="editCateDialogVisible = false">取 消</el-button>
          <el-button
            type="primary"
            @click="editCateNameForm"
          >确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>
<script>
export default {
  data() {
    return {
      //修改商品名字表单数据
      editCateGoodsNameForm: {
        cat_name: '',
        cat_id: ''
      },
      //表单验证规则
      editCateGoodsNameRules: {
        cat_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' },
        ]
      },
      //发起请求需要请求的参数信息
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5
      },
      //获取的商品分类数据树形信息
      cateResultTreeList: [],
      //获取的数据总条数,默认为0
      total: 0,
      //控制添加对话框的弹出
      addCatedialogVisible: false,
      //父级商品分类数据
      parentCateList: [],
      //父级商品选中的值
      cateSelectedOptions: [],
      //控制商品名字修改对话话框的弹出与隐藏
      editCateDialogVisible: false,
      //级联选择器的配置对象
      catePropsObj: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      //提交表单请求所携带的参数
      addCateFormValue: {
        cat_name: '',
        cat_level: 0,
        cat_pid: 0
      },
      //定义添加商品分类验证规则
      addCateRules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
          { min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur' }
        ]
      },
      //为table指定定义
      columns: [
        {
          label: '分类名称',
          prop: 'cat_name'
        },
        {
          label: '是否有效',
          //表示当前自定义的模板列
          type: 'template',
          //表示当前定义模板的名称
          template: 'isOk'
        },
        {
          label: '等级',
          type: 'template',
          template: 'level'
        },
        {
          label: '操作',
          type: 'template',
          template: 'operation'
        }
      ]
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    //获取商品分类列表
    async getCateList() {
      const { data: res } = await this.$http.get('categories', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      // console.log(res.data)
      this.cateResultTreeList = res.data.result
      this.total = res.data.total
    },
    //分页功能实现,默认这个函数会传入一个参数
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getCateList()
    },
    handleCurrentChange(newCurrent) {
      this.queryInfo.pagenum = newCurrent
      this.getCateList()
    },
    //弹出添加分类商品对话框
    addCate() {
      //获取父级商品数据
      this.getParentCateList()
      this.addCatedialogVisible = true
    },
    //获取父级商品分类的名称
    async getParentCateList() {
      const { data: res } = await this.$http.get('categories', {
        params: { type: 2 }
      })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.parentCateList = res.data
      console.log(this.parentCateList)
    },
    //关闭对话框时清除添加商品的表单信息
    clearFromInfo() {
      this.$refs.addCateFormRef.resetFields()
      //清空选中的值
      this.cateSelectedOptions = []
      //清空表单所提交的值
      this.addCateFormValue.cat_name = ''
      this.addCateFormValue.cat_level = 0
      this.addCateFormValue.cat_pid = 0
    },
    //父级商品选中商品触发函数,设置提交表单数据
    cateHandleChange() {
      //判断当前的选中的父级id
      //  console.log(this.cateSelectedOptions);
      if (this.cateSelectedOptions.length > 0) {
        this.addCateFormValue.cat_pid = this.cateSelectedOptions[
          this.cateSelectedOptions.length - 1
        ]

        this.addCateFormValue.cat_level = this.cateSelectedOptions.length
      } else {
        //否者重新赋值为0
        this.addCateFormValue.cat_pid = 0
        this.addCateFormValue.cat_level = 0
      }
    },
    //添加商品
    async addCateGoods() {
      const { data: res } = await this.$http.post(
        'categories',
        this.addCateFormValue
      )
      if (res.meta.status !== 200) {
        this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      this.getCateList()
      this.addCatedialogVisible = false
    },
    //删除商品
    async deleteRightRoles(id) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('取消了本次操作')
      }
      //发起异步请求
      const { data: res } = await this.$http.delete(`categories/${id}`)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      //重新获取数据
      this.getCateList()
    },
    //修改商品名字并做赋值操作
    editCateGoodsName(id, name) {
      // console.log(id,name);
      //将传过来的值赋值给表单数据中的值
      this.editCateGoodsNameForm.cat_name = name
      this.editCateGoodsNameForm.cat_id = id
      this.editCateDialogVisible = true
    },
    //提交修改商品表单数据
    editCateNameForm() {
      //表单预验证
      this.$refs.editCateGoodsNameRef.validate(async vailed => {
        if (!vailed) return
        //否则就发起请求
        const { data: res } = await this.$http.put(
          `categories/${this.editCateGoodsNameForm.cat_id}`,
          {
            cat_name: this.editCateGoodsNameForm.cat_name
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg);
        this.editCateDialogVisible = false;
        this.getCateList()
      })
    },
    //重置修改表单数据
    clearEditFromData() {
      this.$refs.editCateGoodsNameRef.resetFields()
    },
  }
}
</script>
<style lang="less" scoped>
.el-row {
  margin-bottom: 10px;
}
.el-cascader {
  width: 100%;
}
</style>
